<?php

/**
 * Replaces text containing EE variables with values from the exp_global_variables DB table (if they exist)
 */
class Global_variable_replacer
{
	var $globals_lookup = array();

	function Global_variable_replacer($site_id='')
	{
		$this->initGlobalsLookup($site_id);
	}
		
	/**
	 *
	 * Read in all the global variables from exp_global_variables and create a key/value lookup table
	 */
	function initGlobalsLookup($site_id='')
	{
		global $DB, $PREFS;

		$site_id = (empty($site_id) ? $PREFS->core_ini['site_id'] : $site_id);

		$sql = "SELECT * FROM exp_global_variables";		
		if (!empty($site_id))
		{
			$sql .= " WHERE site_id='".$site_id."'";
		}
			$sql .= " ORDER BY variable_name ASC";
		
		$query = $DB->query($sql);
		
		if($query->num_rows > 0)
		{
			foreach($query->result as $row) 
	        {
				$key = $row['variable_name'];
				$value = $row['variable_data'];
				$this->globals_lookup[$key] = $value;
			}
		}
	}
	
	function getReplacedText($text)
	{
		$replacedText = $text;
	
		// if passed text in contains anything that looks like an EE variable, check in the DB global variables for it
		preg_match_all("/{([^}]+)}/", $text, $matches);
		
		$vars = $matches[1];
		
		if (sizeof($vars) > 0)
		{
			foreach ($vars as $key)
			{		
				$global_value = $this->globals_lookup[$key];
//				print("key: $key value: $global_value<br/>");//TMP
				if ($global_value)
				{
					$replacedText = str_replace("{".$key."}", $global_value, $replacedText);
				}
			}
		}
		
		return $replacedText;
	}

} // end class

?>